/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.service.usertask.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.TaskService;
import com.je.bpm.runtime.shared.RemoteCallServeManager;
import com.je.bpm.runtime.shared.operator.validator.PayloadValidErrorException;
import com.je.bpm.runtime.task.TaskOperatorService;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.service.MetaBusService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.PlatformService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.FunctionService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.servicecomb.JECloud;
import com.je.servicecomb.RpcSchemaFactory;
import com.je.workflow.rpc.dictionary.WorkFlowRemoteCallServeManager;
import com.je.workflow.service.button.ButtonService;
import com.je.workflow.service.user.WorkFlowUserService;
import com.je.workflow.service.usertask.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

import static com.je.servicecomb.JECloud.PRODUCT_CORE_RBAC;
import static com.je.workflow.service.usertask.vo.UserTaskVo.JudgmentDay;

@Service
public class MonitorServiceImpl implements MonitorService {

    private static final String[] END_STATUS = new String[]{"END", "INVALID"};

    @Autowired
    private MetaService metaService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private WorkFlowUserService workFlowUserService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RemoteCallServeManager remoteCallServeManager;
    @Autowired
    private ButtonService buttonService;
    @Autowired
    private FunctionService functionService;
    @Autowired
    private TaskOperatorService taskOperatorService;

    @Override
    public Page load(BaseMethodArgument param, HttpServletRequest request) {
        if (param.getLimit() == 0) {
            param.setLimit(-1);
        }
        Page page = new Page(param.getPage(), param.getLimit());
        String funcCode = param.getFuncCode();
        //内容和功能名称是经过转义的，这里重新jquery
        if (!Strings.isNullOrEmpty(param.getjQuery())) {
            buildQuery(param);
        }
        ConditionsWrapper wrapper = platformService.buildWrapper(param, request);
        List<Map<String, Object>> list = this.metaService.load(funcCode, page, wrapper);
        for (Map<String, Object> map : list) {
            if (!Arrays.asList(END_STATUS).contains(map.get("STATE"))) {
                map.put("SY_CREATETIME", "");
                String piId = String.valueOf(map.get("EXECUTION_PIID"));
                List<DynaBean> userNameList = metaService.select("JE_WORKFLOW_RN_TASK", ConditionsWrapper.builder()
                        .eq("TASK_PIID", piId).eq("TASK_HANDLE", "0"), "ASSIGNEE_NAME");
                Set<String> PENDING_PERSON = new HashSet<>();
                for (DynaBean user : userNameList) {
                    PENDING_PERSON.add(user.getStr("ASSIGNEE_NAME"));
                }
                map.put("PENDING_PERSON", String.join(",", PENDING_PERSON));
            } else {
                map.put("EXECUTION_NODE_NAME", "结束节点");
            }
            if (map.get("EXECUTION_CONTENT") == null || map.get("EXECUTION_CONTENT").toString().length() == 0) {
                map.put("EXECUTION_CONTENT", buildTitle(String.valueOf(map.get("EXECUTION_TITLE")), String.valueOf(map.get("EXECUTION_START_TIME"))));
            }
        }
        page.setRecords(list);
        return page;
    }

    private void buildQuery(BaseMethodArgument param) {
        String strJquery = param.getjQuery();
        strJquery = strJquery.replace("", "")
                .replace("EXECUTION_STARTER_NAME", "EXECUTION_CONTENT")
                .replace("EXECUTION_NODE_NAME", "EXECUTION_TITLE");
        param.setjQuery(strJquery);

//        JSONObject jqueryJ = JSONObject.parseObject(param.getjQuery());
//        JSONArray jsonArray = JSONArray.parse(String.valueOf(jqueryJ.get("custom")));
//        if (jsonArray.size() > 0) {
//            JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(0).toString());
//            String paramValue = JSONObject.parseObject(JSONArray.parse(jsonObject.get("value").toString()).get(0).toString()).get("value").toString();
//            jsonObject.put("type", "and");
//            jsonObject.put("cn", "and");
//            String[] codeArray = new String[]{"PROCESS_NAME", "FUNC_NAME", "EXECUTION_CONTENT", "EXECUTION_TITLE"};
//            JSONArray valueArray = new JSONArray();
//            for (String code : codeArray) {
//                JSONObject value = new JSONObject();
//                value.put("code", code);
//                value.put("value", paramValue);
//                value.put("type", "like");
//                value.put("cn", "or");
//                valueArray.add(value);
//            }
//            jsonObject.put("value", valueArray);
//            jqueryJ.put("custom", jsonObject);
//            param.setjQuery(jqueryJ.toJSONString());
//        }
    }

    @Override
    @Transactional
    public void clearDirtyData() {
        //EXECUTION_PRODUCT_CODE=产品code BUSINESS_KEY=主键
//        new Thread(() -> {
        String monitorSql = "SELECT EXECUTION_PRODUCT_CODE,BUSINESS_KEY,TABLE_CODE,STATE FROM JE_WORKFLOW_MONITOR";
        List<Map<String, Object>> monitorData = metaService.selectSql(monitorSql);
        for (Map<String, Object> map : monitorData) {
            String productCode = (String) map.get("EXECUTION_PRODUCT_CODE");
            String businessKey = (String) map.get("BUSINESS_KEY");
            String tableCode = (String) map.get("TABLE_CODE");
            String state = (String) map.get("STATE");
            int removeB = executeRemoteQuery(productCode, tableCode, businessKey);
            if (removeB == 1) {
                deleteExecution(state, businessKey);
            }
        }
//        }).start();
    }


    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Integer> runCount = getAllCount();
        Map<String, Object> timeCount = getTimeCount(runCount);
        Map<String, Integer> typeCount = getTypeCount();
        result.put("run", runCount);
        result.put("time", timeCount);
        result.put("type", typeCount);
        return result;
    }

    @Override
    public void processAllHandover(String assignee, String toAssignee) {
//        批量修改业务数据
        Map<String, List<DynaBean>> listMap = getUpdateList(assignee, toAssignee, "");

        //update jeCloud待办表
        DynaBean jeCloudBean = new DynaBean();
        jeCloudBean.setStr("ASSIGNEE_NAME", workFlowUserService.getUserNameById(toAssignee));
        jeCloudBean.setStr("ASSIGNEE_ID", toAssignee);
        metaService.update(jeCloudBean, ConditionsWrapper.builder().table("JE_WORKFLOW_RN_TASK").eq("ASSIGNEE_ID", assignee));
        //update 流程待办表
        DynaBean bpmBean = new DynaBean();
        bpmBean.setStr("ASSIGNEE_", toAssignee);
        metaService.update(bpmBean, ConditionsWrapper.builder().table("act_hi_taskinst")
                .apply(String.format(" and id_ in (select id_ from act_ru_task where ASSIGNEE_ = '%s')", assignee)));
        metaService.update(bpmBean, ConditionsWrapper.builder().table("act_ru_task").eq("ASSIGNEE_", assignee));
        for (String key : listMap.keySet()) {
            List<DynaBean> updateList = listMap.get(key);
            updateProdBeanAssigneeInfo(key, updateList);
        }

        for (String key : listMap.keySet()) {
            List<DynaBean> updateList = listMap.get(key);
            for (DynaBean dynaBean : updateList) {
                if (dynaBean.get("muTask") instanceof Boolean && (Boolean) dynaBean.get("muTask")) {
                    taskService.multiTaskHandover(dynaBean.getStr("ASSIGNEE_"), toAssignee, dynaBean.getStr("ID_"));
                }
            }
        }
    }


    @Override
    public void processHandoverByIds(String toAssignee, String ids) {
        //批量修改业务数据
        Map<String, List<DynaBean>> listMap = getUpdateList("", toAssignee, ids);

        //update jeCloud待办表
        DynaBean jeCloudBean = new DynaBean();
        jeCloudBean.setStr("ASSIGNEE_NAME", workFlowUserService.getUserNameById(toAssignee));
        jeCloudBean.setStr("ASSIGNEE_ID", toAssignee);
        metaService.update(jeCloudBean, ConditionsWrapper.builder().table("JE_WORKFLOW_RN_TASK")
                .in("TASK_ACTIVITI_TASK_ID", ids.split(",")));
        //update 流程待办表
        DynaBean bpmBean = new DynaBean();
        bpmBean.setStr("ASSIGNEE_", toAssignee);
        metaService.update(bpmBean, ConditionsWrapper.builder().table("act_ru_task").in("ID_", ids.split(",")));
        metaService.update(bpmBean, ConditionsWrapper.builder().table("act_hi_taskinst").in("ID_", ids.split(",")));

        for (String key : listMap.keySet()) {
            List<DynaBean> updateList = listMap.get(key);
            updateProdBeanAssigneeInfo(key, updateList);
        }

        for (String key : listMap.keySet()) {
            List<DynaBean> updateList = listMap.get(key);
            for (DynaBean dynaBean : updateList) {
                if (dynaBean.get("muTask") instanceof Boolean && (Boolean) dynaBean.get("muTask")) {
                    taskService.multiTaskHandover(dynaBean.getStr("ASSIGNEE_"), toAssignee, dynaBean.getStr("ID_"));
                }
            }
        }
        //处理钉钉待办
        boolean isPushDindToDo = false;
        if (isPushDindToDo) {
            for (String key : listMap.keySet()) {
                List<DynaBean> updateList = listMap.get(key);
                for (DynaBean dynaBean : updateList) {
                    Map<String, Object> bean = new HashMap<>();
                    bean.put("SY_AUDFLAG", "WAIT");
                    String pdid = dynaBean.getStr("EXECUTION_PDID");
                    String piid = dynaBean.getStr("EXECUTION_PIID");
                    String pkValue = dynaBean.getStr("BUSINESS_KEY");
                    buttonService.updateDingTalkTask(pdid, pkValue, bean, piid);
                }
            }
        }
    }

    @Override
    public List<JSONObject> getRunNodes(String piid) {
        return taskService.getRunNodes(piid);
    }

    @Override
    public List<JSONObject> getAllNode(String piid) {
        return taskService.getAllNode(piid);
    }

    @Override
    public String adjustRunningNode(String piid, String currentNodeId, String toNodeId, String prod, String tableCode, String beanId
            , String funcCode, String funcId) {
        Map<String, Object> bean = new HashMap<>();
        bean = getBean(prod, beanId, tableCode);
        taskService.adjustRunningNode(piid, currentNodeId, toNodeId, bean, prod);
        bean = getBean(prod, beanId, tableCode);

        if (Strings.isNullOrEmpty(funcId)) {
            DynaBean funcInfo = functionService.findFunction(funcCode);
            funcId = funcInfo.getStr("JE_CORE_FUNCINFO_ID");
        }

        buttonService.updateBusinessWorkFlowInfo(bean, beanId, prod, tableCode, funcCode, funcId, false);
        metaService.delete("JE_WORKFLOW_EXCEPTIONAL", ConditionsWrapper.builder().eq("BUSINESS_KEY", beanId));
        return "调整成功！";
    }

    @Override
    public String adjustNodeAssignee(String piid, String currentNodeId, String userIds, String userNames, String head,
                                     String headName, String prod, String tableCode, String beanId, String funcCode, String funcId) {
        JSONArray assigneeJson = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nodeId", currentNodeId);
        jsonObject.put("assignee", userIds);
        assigneeJson.add(jsonObject);
        List<DynaBean> list1 = metaService.select("JE_WORKFLOW_RN_TASK", ConditionsWrapper.builder()
                .eq("TASK_NODE_ID", currentNodeId)
                .eq("task_piid", piid)
        );
        String taskId = list1.get(0).getStr("TASK_ACTIVITI_TASK_ID");

        try {
            //多人节点调整人员
            if (currentNodeId.startsWith("countersign") || currentNodeId.startsWith("batchtask")) {
                taskOperatorService.personnelAdjustments(prod, piid, beanId, taskId, assigneeJson.toJSONString());
            } else {
                taskOperatorService.taskAdjustingPersonnel(prod, piid, beanId, taskId, assigneeJson.toJSONString());
                DynaBean beanMap = new DynaBean("JE_WORKFLOW_RN_TASK", true);
                beanMap.setStr("ASSIGNEE_ID", userIds);
                beanMap.setStr("ASSIGNEE_NAME", userNames);
                metaService.update(beanMap, ConditionsWrapper.builder()
                        .eq("TASK_ACTIVITI_TASK_ID", taskId));
            }
            //更换负责人
            if (!Strings.isNullOrEmpty(head)) {
                try {
                    JSONArray headJson = new JSONArray();
                    JSONObject headObject = new JSONObject();
                    headObject.put("nodeId", currentNodeId);
                    headObject.put("assignee", head);
                    headJson.add(headObject);
                    taskOperatorService.changeAssignee(prod, piid, beanId, taskId, headJson.toJSONString());
                } catch (PayloadValidErrorException e) {
                    e.printStackTrace();
                }
            }
        } catch (PayloadValidErrorException e) {
            e.printStackTrace();
        }

        Map<String, Object> bean = getBean(prod, beanId, tableCode);
        if (Strings.isNullOrEmpty(funcId)) {
            DynaBean funcInfo = functionService.findFunction(funcCode);
            funcId = funcInfo.getStr("JE_CORE_FUNCINFO_ID");
        }
        buttonService.updateBusinessWorkFlowInfo(bean, beanId, prod, tableCode, funcCode, funcId, false);
        metaService.delete("JE_WORKFLOW_EXCEPTIONAL", ConditionsWrapper.builder().eq("BUSINESS_KEY", beanId));
        return "人员调整成功！";
    }

    private Map<String, Object> getBean(String prod, String beanId, String tableCode) {
        Object dynaBeanObject = remoteCallServeManager.doGet(prod, beanId, tableCode, null);
        if (dynaBeanObject == null) {
            throw new ActivitiException("获取bean信息异常！");
        }
        Map<String, Object> map = (Map<String, Object>) dynaBeanObject;
        Map<String, Object> bean = (Map<String, Object>) map.get("values");
        return bean;
    }

    public Map<String, List<DynaBean>> getUpdateList(String assignee, String toAssignee, String ids) {
        Map<String, List<DynaBean>> listMap = new HashMap<>();
        List<DynaBean> list = new ArrayList<>();
        if (!Strings.isNullOrEmpty(assignee)) {
            list = metaService.select("JE_WORKFLOW_PROCESS_HANDOVER", ConditionsWrapper.builder()
                            .eq("ASSIGNEE_", assignee),
                    "EXECUTION_PRODUCT_CODE,TABLE_CODE,EXECUTION_PROCESS_KEY,ASSIGNEE_,BUSINESS_KEY,TASK_DEF_KEY_,ID_,EXECUTION_PDID ,EXECUTION_PIID");
        } else if (!Strings.isNullOrEmpty(ids)) {
            list = metaService.select("JE_WORKFLOW_PROCESS_HANDOVER", ConditionsWrapper.builder()
                            .in("ID_", ids.split(",")),
                    "EXECUTION_PRODUCT_CODE,TABLE_CODE,EXECUTION_PROCESS_KEY,ASSIGNEE_,BUSINESS_KEY,TASK_DEF_KEY_,ID_,EXECUTION_PDID ,EXECUTION_PIID");
        }
        for (DynaBean dynaBean : list) {
            String prod = dynaBean.getStr("EXECUTION_PRODUCT_CODE");
            List<DynaBean> beans = listMap.computeIfAbsent(prod, k -> new ArrayList<>());
            String userName = workFlowUserService.getUserNameById(dynaBean.getStr("ASSIGNEE_"));
            String newUserName = workFlowUserService.getUserNameById(toAssignee);
            dynaBean.setStr("USER_NAME", userName);
            dynaBean.setStr("NEW_USER_NAME", newUserName);
            dynaBean.setStr("NEW_ASSIGNEE_", toAssignee);
            if (!Strings.isNullOrEmpty(dynaBean.getStr("TASK_DEF_KEY_"))
                    && (
                    dynaBean.getStr("TASK_DEF_KEY_").startsWith("batchtask")
                            || dynaBean.getStr("TASK_DEF_KEY_").startsWith("countersign"))) {
                dynaBean.set("muTask", true);
            }
            beans.add(dynaBean);
        }
        return listMap;
    }

    private Map<String, Integer> getAllCount() {
        Map<String, Integer> map = new HashMap<>();
        List<Map<String, Object>> allList = metaService.selectSql("SELECT COUNT(*) AS COUNT FROM JE_WORKFLOW_MONITOR");
        Object allCount = allList.get(0).get("COUNT");
        map.put("all", Integer.parseInt(String.valueOf(allCount)));
        List<Map<String, Object>> wait = metaService.selectSql("SELECT COUNT(*) AS COUNT FROM JE_WORKFLOW_MONITOR WHERE  STATE = 'WAIT'");
        map.put("wait", Integer.parseInt(String.valueOf(wait.get(0).get("COUNT"))));
        List<Map<String, Object>> abnormal = metaService.selectSql("SELECT COUNT(*) AS COUNT FROM JE_WORKFLOW_EXCEPTIONAL WHERE  EXCEPTIONAL_TYPE != 'user'");
        map.put("abnormal", Integer.parseInt(String.valueOf(abnormal.get(0).get("COUNT"))));
        List<Map<String, Object>> invalidHandler = metaService.selectSql("SELECT COUNT(*) AS COUNT FROM JE_WORKFLOW_EXCEPTIONAL WHERE  EXCEPTIONAL_TYPE = 'user'");
        map.put("invalidHandler", Integer.parseInt(String.valueOf(invalidHandler.get(0).get("COUNT"))));
        return map;
    }

    private Map<String, Object> getTimeCount(Map<String, Integer> runCount) {
        Map<String, Object> map = new HashMap<>();
        //所有流程
        Map<String, Integer> all = new HashMap<>();
        all.put("all", runCount.get("all"));
        all.put("wait", runCount.get("wait"));
        map.put("all", all);
        //近一年
        Map<String, Integer> year = new HashMap<>();
        year.put("all", Integer.parseInt(String.valueOf(metaService.selectSql("SELECT COUNT(*) AS COUNT\n" +
                "        FROM JE_WORKFLOW_MONITOR\n" +
                "        WHERE EXECUTION_START_TIME >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) ").get(0).get("COUNT"))));
        year.put("wait", Integer.parseInt(String.valueOf(metaService.selectSql("SELECT COUNT(*) AS COUNT\n" +
                "        FROM JE_WORKFLOW_MONITOR\n" +
                "        WHERE EXECUTION_START_TIME >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND STATE = 'WAIT'").get(0).get("COUNT"))));
        map.put("year", year);
        //近一月
        Map<String, Integer> month = new HashMap<>();
        month.put("all", Integer.parseInt(String.valueOf(metaService.selectSql("SELECT COUNT(*) AS COUNT\n" +
                "        FROM JE_WORKFLOW_MONITOR\n" +
                "        WHERE EXECUTION_START_TIME >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) ").get(0).get("COUNT"))));
        month.put("wait", Integer.parseInt(String.valueOf(metaService.selectSql("SELECT COUNT(*) AS COUNT\n" +
                "        FROM JE_WORKFLOW_MONITOR\n" +
                "        WHERE EXECUTION_START_TIME >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND STATE = 'WAIT'").get(0).get("COUNT"))));
        map.put("month", month);
        //近一周
        Map<String, Integer> week = new HashMap<>();
        week.put("all", Integer.parseInt(String.valueOf(metaService.selectSql("SELECT COUNT(*) AS COUNT\n" +
                "        FROM JE_WORKFLOW_MONITOR\n" +
                "        WHERE EXECUTION_START_TIME >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK) ").get(0).get("COUNT"))));
        week.put("wait", Integer.parseInt(String.valueOf(metaService.selectSql("SELECT COUNT(*) AS COUNT\n" +
                "        FROM JE_WORKFLOW_MONITOR\n" +
                "        WHERE EXECUTION_START_TIME >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK) AND STATE = 'WAIT'").get(0).get("COUNT"))));
        map.put("week", week);
        return map;
    }

    private Map<String, Integer> getTypeCount() {
        Map<String, Integer> result = new HashMap<>();
        List<Map<String, Object>> list = metaService.selectSql("SELECT COUNT(*) AS COUNT,PROCESSINFO_TYPE_CODE,PROCESSINFO_TYPE_NAME FROM JE_WORKFLOW_MONITOR_TYPE" +
                " GROUP BY PROCESSINFO_TYPE_CODE,PROCESSINFO_TYPE_NAME");
        for (Map<String, Object> map : list) {
            if (Strings.isNullOrEmpty(String.valueOf(map.get("PROCESSINFO_TYPE_CODE")))) {
                continue;
            }
            String count = String.valueOf(map.get("COUNT"));
            result.put(String.valueOf(map.get("PROCESSINFO_TYPE_NAME")), Integer.parseInt(count));
        }
        return result;
    }

    private void deleteExecution(String state, String businessKey) {
        if (Arrays.asList(END_STATUS).contains(state)) {
            List<DynaBean> executions = metaService.select("JE_WORKFLOW_HI_EXECUTION",
                    ConditionsWrapper.builder().eq("BUSINESS_KEY", businessKey));
            for (DynaBean dynaBean : executions) {
                dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_WORKFLOW_HI_EXECUTION_RECYCLE_BIN");
                metaService.insert(dynaBean);
                List<DynaBean> tasks = metaService.select("JE_WORKFLOW_HI_TASK",
                        ConditionsWrapper.builder().eq("JE_WORKFLOW_HI_EXECUTION_ID", dynaBean.getPkValue()));
                for (DynaBean task : tasks) {
                    task.setStr(BeanService.KEY_TABLE_CODE, "JE_WORKFLOW_HI_TASK_RECYCLE_BIN");
                    metaService.insert(task);
                }
                metaService.executeSql("DELETE FROM JE_WORKFLOW_HI_TASK WHERE JE_WORKFLOW_HI_EXECUTION_ID={0}", dynaBean.getPkValue());
            }
            metaService.executeSql("DELETE FROM JE_WORKFLOW_HI_EXECUTION WHERE BUSINESS_KEY={0}", businessKey);
        } else {
            List<DynaBean> executions = metaService.select("JE_WORKFLOW_RN_EXECUTION",
                    ConditionsWrapper.builder().eq("BUSINESS_KEY", businessKey));
            for (DynaBean dynaBean : executions) {
                dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_WORKFLOW_RN_EXECUTION_RECYCLE_BIN");
                metaService.insert(dynaBean);
                List<DynaBean> tasks = metaService.select("JE_WORKFLOW_RN_TASK",
                        ConditionsWrapper.builder().eq("JE_WORKFLOW_RN_EXECUTION_ID", dynaBean.getPkValue()));
                for (DynaBean task : tasks) {
                    task.setStr(BeanService.KEY_TABLE_CODE, "JE_WORKFLOW_RN_TASK_RECYCLE_BIN");
                    metaService.insert(task);
                }
                metaService.executeSql("DELETE FROM JE_WORKFLOW_RN_TASK WHERE JE_WORKFLOW_RN_EXECUTION_ID={0}", dynaBean.getPkValue());
            }
            metaService.executeSql("DELETE FROM JE_WORKFLOW_RN_EXECUTION WHERE BUSINESS_KEY={0}", businessKey);
        }
    }

    protected int executeRemoteQuery(String product, String tableCode, String pkValue) {
        if (JECloud.PRODUCT_CORE_WORKFLOW.equals(product) || JECloud.PRODUCT_CORE_META.equals(product) || PRODUCT_CORE_RBAC.equals(product)) {
            return 0;
        }
        try {
            MetaBusService metaBusService = RpcSchemaFactory.getRemoteProvierClazz(product, "metaBusService", MetaBusService.class);
            if (metaBusService.selectDataExistsByPkValue(tableCode, pkValue)) {
                return 0;
            }
        } catch (Exception e) {
            return 0;
        }
        return 1;
    }

    public void updateProdBeanAssigneeInfo(String prod, List<DynaBean> list) {
        WorkFlowRemoteCallServeManager workFlowRemoteCallServeManager =
                RpcSchemaFactory.getRemoteProvierClazz(prod, "workFlowRemoteCallServeManager",
                        WorkFlowRemoteCallServeManager.class);
        workFlowRemoteCallServeManager.updateListBeanWFAssignee(list);
    }


    private static String buildTitle(String title, String startTime) {
        try {
            String day = JudgmentDay(startTime);
            if (day == null) {
                day = startTime.substring(0, 10);
            }
            try {
                title = String.format(title, "（" + day + "）");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return title;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return title;
    }

}
